package com.ybkj.daijia.server.event.listener.zhuan;

import com.ybkj.daijia.PushDataV4;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.gexin.GeTuiEmployV4;
import com.ybkj.daijia.api.jpush.JiGuangEmployV4;
import com.ybkj.daijia.server.ZhuanOrderTimerTask;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderCreateEvent;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.scheduler.ThreadControl;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SmsTempletService;
import com.ybkj.daijia.server.service.SuperviceService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import com.ybkj.daijia.server.zhuan.Order;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
@Slf4j
public class ZhuanOrderCreateEventListener implements ApplicationListener<ZhuanOrderCreateEvent> {


    @Autowired
    private CompanyService companyService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private ZhuancheService zhuanService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private SmsTempletService smsTempletService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private SuperviceService superviceService;
    @Autowired
    private ZhuancheService zhuancheService;

    @Override
    @Async
    public void onApplicationEvent(ZhuanOrderCreateEvent event) {
        Long orderId = (Long) event.getSource();
        Order order = zhuanService.findOne(orderId);

        Long refusedEmployId = event.getRefusedEmployId();

    log.debug("order zhuanche created event:{}", order.getOrderNo());
    Setting setting = settingUtils.get();
    // 推送数据到浏览器
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("type", "zhuancheNewOrders_company");
    Company mainCompany = companyService.getMain();
    WebSocketSend.boardcastToCompany(jsonObject, order.getCompanyId(), mainCompany.getId());

    //预约订单逻辑判断
	Integer isBook = order.getBookStatus();
	Date serverTime = order.getServerTime();
	Date now = new Date();
/*	if (isBook > 0) {
		Long yuyueTimes = setting.getZhuanYuyueTime().longValue();
		Long yuyueMax = setting.getZhuanYuyueMax().longValue();
		Long minutes = (serverTime.getTime() - now.getTime())/60000;
		if (minutes > yuyueTimes) {
			return;
		}
	}*/
    
    if (setting.isAllowRushOrderZhuanche()) { //开启允许司机抢单
      Double rushOrderKm1 = setting.getRushOrderKm1();
      Double rushOrderKm2 = setting.getRushOrderKm2();
      Double rushOrderKm3 = setting.getRushOrderKm3();
      Integer rushOrderTime1 = setting.getRushOrderTime1();
      Integer rushOrderTime2 = setting.getRushOrderTime2();
      Integer rushOrderTime3 = setting.getRushOrderTime3();
      try {
        // 第一阶段
        Thread.sleep(rushOrderTime1 * 1000);
        if (order.getStatus().equals(Order.ORDER_STATUS_NEW)) {
          List<Driver> drivers =
              driverService.zhuanListDrivers(order.getStartLng(), order.getStartLat(), rushOrderKm1,order.getPassengerId(),order.getCarTypeId());
          if (!CollectionUtils.isEmpty(drivers)) {
            for (Driver rushDriver : drivers) {
              if(zhuancheService.findDriverBusy(rushDriver.getId(),order.getBookStatus(),orderId)){
              if (!rushDriver.getIsFreeze() && rushDriver.getStatus().equals(Driver.DRIVER_ONLINE)) {
                if (rushDriver.getDriverJobType().equals(Driver.DriverJobType.all)
                        || rushDriver.getDriverJobType().toString()
                        .contains(Driver.DriverJobType.zhuanche.toString())) {
                  if (null == refusedEmployId || refusedEmployId != rushDriver.getId()) {//拒单司机不再推送
                    pushNewOrder(order, rushDriver, setting);
                  }
                }
              }
              }
            }
          }

          // 第二阶段
          Thread.sleep(rushOrderTime2 * 1000);
          order = zhuanService.findOne(orderId);
          if (order.getStatus().equals(Order.ORDER_STATUS_NEW)) {
            drivers =
                driverService.zhuanListDrivers(order.getStartLng(), order.getStartLat(), rushOrderKm2,order.getPassengerId(),order.getCarTypeId());
            if (!CollectionUtils.isEmpty(drivers)) {
              for (Driver rushDriver : drivers) {
                if(zhuancheService.findDriverBusy(rushDriver.getId(),order.getBookStatus(),orderId)){
                if (!rushDriver.getIsFreeze()
                    && rushDriver.getStatus().equals(Driver.DRIVER_ONLINE)) {
                      if (rushDriver.getDriverJobType().equals(Driver.DriverJobType.all)
                          || rushDriver.getDriverJobType().toString()
                              .contains(Driver.DriverJobType.zhuanche.toString())) {
                        if (null == refusedEmployId || refusedEmployId != rushDriver.getId()) {//拒单司机不再推送
                          pushNewOrder(order, rushDriver, setting);
                        }
                      }
                  }
                }
              }
            }

            // 第三阶段
            Thread.sleep(rushOrderTime3 * 1000);
            order = zhuanService.findOne(orderId);
            if (order.getStatus().equals(Order.ORDER_STATUS_NEW)) {
              drivers =
                  driverService.zhuanListDrivers(order.getStartLng(), order.getStartLat(), rushOrderKm3,order.getPassengerId(),order.getCarTypeId());
              if (!CollectionUtils.isEmpty(drivers)) {
                for (Driver rushDriver : drivers) {
                  if(zhuancheService.findDriverBusy(rushDriver.getId(),order.getBookStatus(),orderId)){
                  if (!rushDriver.getIsFreeze()
                      && rushDriver.getStatus().equals(Driver.DRIVER_ONLINE)) {
                    if (rushDriver.getDriverJobType().equals(Driver.DriverJobType.all)
                            || rushDriver.getDriverJobType().toString()
                            .contains(Driver.DriverJobType.zhuanche.toString())) {
                      if (null == refusedEmployId || refusedEmployId != rushDriver.getId()) {//拒单司机不再推送
                        pushNewOrder(order, rushDriver, setting);
                      }
                    }
                  }
                  }
                }
              }
            }

          }

        }


      } catch (Exception e) {
        e.printStackTrace();
        log.debug("push error : " + e.getMessage());
      }
    } else if (setting.isAutoPaidanZhuanche()) { // 开启专车自动派单
        //专车订单自动派单定时器
        Timer timer = new Timer();
        ZhuanOrderTimerTask orderTimerTask=new ZhuanOrderTimerTask(
                setting.getAutoPaidanKm1(),setting.getAutoPaidanTime1(),
                setting.getAutoPaidanKm2(),setting.getAutoPaidanTime2(),
                setting.getAutoPaidanKm3(),setting.getAutoPaidanTime3(),
                applicationEventMulticaster,
                order.getId(),order.getStartLat(),order.getStartLng(),1
        );
        
        Integer howLong=setting.getAutoPaidanTime1();
//        if(order.getServerTime().getTime()-System.currentTimeMillis()>1000*60*30){
//            howLong=(int) (order.getServerTime().getTime()-System.currentTimeMillis()-1000*60*30)/1000;
//        }
        timer.schedule(orderTimerTask, howLong*1000);
        ThreadControl.TaskMaps.put("task_"+order.getId(), timer);

    }
    
    //推送客户端下单至监管平台
    superviceService.pushDdjs(order);

  }

  /**
   * 抢单推送.
   */
  private void pushNewOrder(Order newOrder, Driver rushDriver, Setting setting) {
    try {

      PushDataV4 pushDataV4 = new PushDataV4();
      pushDataV4.setCode("0X02");
      pushDataV4.setData(newOrder.getId());
      pushDataV4.setType("0X01");
      pushDataV4.setSound("beep_2");
      Map<String, String> extra = new HashMap<String, String>();
      extra.put("content", "又有新工单可以抢啦");
      pushDataV4.setExtra(extra);

      boolean getuiOnline = false;
      if (StringUtils.isNotBlank(rushDriver.getUserID())) {
        getuiOnline = GeTuiEmployV4.getClientOnline(rushDriver.getUserID(), settingUtils.get());
      }

      if (getuiOnline) {
        GeTuiEmployV4.push(rushDriver, pushDataV4, setting);
      } else {
        if (StringUtils.isNotBlank(rushDriver.getRegistrationId())) {
          JiGuangEmployV4.push(rushDriver, pushDataV4, setting);
        }
      }

    } catch (IOException e) {
      log.debug("push error : " + e.getMessage());
    }
  }

}
